import pandas as pd
import os
import csv
import sys
import argparse
import json
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.filters import FilterColumn, CustomFilter, CustomFilters


default_config = {
  "file_paths": { #店铺, paypal,云汇等文件路径
      "excel_files": [],
      "paypal_csv_files": [],
      "air_csv_files": []
  },
  "output": { #导出名, 以及相关设置
      "export_file_name": "",
      "auto_name": True
  },
  # 文件头行判断-关键词
  "keywords":['订单编号','支付订单号','交易号','交易编号', '货币单位', '订单总价'],
  "known_channels": ["长沙", "华宁", "尼彩"], #csv 来源判断关键词,默认会取csv前两个字符
  # 基础配置信息 
  "main_data": {
      "header": [ #店铺表头
          "支付订单号", "货币单位", "订单总价", "商品总价", "优惠金额", "物流费用",
          "支付状态", "支付方式1", "支付渠道1", "支付金额1", "最后一次互动来源","订单确认时间"
      ],
      "numeric_fields": ["订单总价", "商品总价", "优惠金额", "物流费用"], #店铺数字转换
      "payment_status_filter": ["部分退款", "已支付"], #店铺支付状态筛选

      "paypal_header": [ #paypal 表头
          "交易号", "币种", "总额", "费用", "净额", "类型", "状态", "来源",
          "Transaction ID","Currency","Gross","Fee","Net","Type","Status"
      ],
      "paypal_checkout_types": [ #palpal 类型筛选
          "快速结账付款", "直接信用卡付款", "预先批准付款账单用户付款",
          "Express Checkout Payment","Direct Credit Card Payment","PreApproved Payment Bill User Payment"
      ],
      "paypal_checkout_status":["已完成","Completed"],
      "paypal_checkout_neednum":["总额", "费用", "净额","Gross","Fee","Net"],

      "air_header": [ #云汇表头
          "交易编号", "交易币种", "交易金额", "授权状态返回描述", "交易状态", "来源"
      ],
      "air_checkout_types": [ #云汇 交易状态筛选
          "FULLY REFUNDED", "PARTIALLY REFUNDED", "SUCCEEDED", "DISPUTED"
      ],
  },
}

# 全局配置变量, 全局变量如果时存赋值时, 可以直接不申明, 取值
config = default_config

def load_config(config_path="config.json"):
    """
    加载配置文件，如果文件不存在则创建默认配置
    """ 
    global config
    try:
        if os.path.exists(config_path):
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                print(f"已加载配置文件: {config_path}")
                return config
        else:
            # 创建默认配置文件
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, ensure_ascii=False, indent=2)
                print(f"已创建默认配置文件: {config_path}")
            return default_config
    except Exception as e:
        print(f"加载配置文件出错: {e}，使用默认配置")
        return default_config


def create_filename(filename):
    """
    创建唯一的文件名，如果文件已存在则添加序号
    相当于JavaScript中的createFileName函数
    """
    name = filename
    count = 1
    base_name, extension = os.path.splitext(filename)
    while os.path.exists(name):
        name = f"{base_name}({count}){extension}"
        count += 1
    return name


def determine_channel(file_path):
    global config
    knows = config.get("known_channels", ['长沙', '华宁','尼彩'])
    file_name = os.path.basename(file_path)
    return next(
        (item for item in knows if item in file_name),
        file_name[:2] if len(file_name) > 2 else ""
    )

def get_xlsx_data(file_path="", header_row=None):
    """
    读取Excel文件并转换为JSON对象数组，支持动态表头检测
    """
    global config
    print(f"读取文件: {file_path}")
    df = pd.read_excel(file_path, header=None)  # 先不指定表头
    
    # 自动检测表头行
    if header_row is None:
        keywords = config.get("keywords", {'订单编号','支付订单号','交易号','交易编号', '货币单位', '订单总价'})
        for i in range(min(9, len(df))):  # 扫描前9行
            if any(str(cell).strip() in keywords for cell in df.iloc[i]):
                header_row = i
                break
        else:
            header_row = 0
    
    # 重新读取数据并设置表头
    df = pd.read_excel(file_path, header=header_row)
    # df = df.dropna(how='all').reset_index(drop=True)  # 删除空行
       # 直接转换DataFrame为字典列表
    new_arr = df.iloc[0:].to_dict('records')
    print(len(new_arr),'行')
    # 处理字段重命名
    for item in new_arr:
        item['来源'] = determine_channel(file_path)
        new_item = {}
        # 优先处理并添加支付订单号字段
        for key in list(item.keys()):
            if isinstance(key, str) and "支付订单号" in key:
                # item["支付订单号"] = item.pop(key)
                new_item["支付订单号"] = item[key]
                break
        # 添加其他字段并保持原有顺序
        for key, value in item.items():
            if key not in new_item:
                new_item[key] = value
        item.clear()
        item.update(new_item)
   
    return new_arr


def get_column_index(worksheet, column_name):
    """
    获取列名对应的索引
    相当于JavaScript中的getColumnIndex函数
    """
    for i, cell in enumerate(next(worksheet.iter_rows(min_row=1, max_row=1))):
        if cell.value == column_name:
            return i
    return -1


def is_last_day_of_month(date_str):
    """
    判断日期是否为月末最后一天
    相当于JavaScript中的isLastDayOfMonth函数
    """
    if not date_str:
        return False
    
    # 尝试解析日期字符串
    try:
        from datetime import datetime
        # 尝试标准格式解析
        date = datetime.strptime(str(date_str), '%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        try:
            # 尝试其他常见格式
            import re
            # 例如：2025-4-30 或 2025.4.30 或 2025年4月30日
            patterns = [
                r'^(\d{4})[-./年](\d{1,2})[-./月](\d{1,2})',
                r'^(\d{1,2})[-./月](\d{1,2})[-./日],(\d{4})'
            ]
            
            for pattern in patterns:
                match = re.search(pattern, str(date_str))
                if match:
                    year, month, day = match.groups()
                    from datetime import datetime
                    parsed_date = datetime(int(year), int(month), int(day))
                    
                    # 检查是否为月末
                    import calendar
                    last_day = calendar.monthrange(parsed_date.year, parsed_date.month)[1]
                    return int(day) == last_day
            
            return False
        except:
            return False
    else:
        # 标准日期格式解析成功
        # 检查是否为月末
        from datetime import datetime, timedelta
        next_day = date + timedelta(days=1)
        return date.month != next_day.month

def export_excel(data_sheets, export_file_name):
    """
    导出数据到Excel文件，支持自动筛选功能
    相当于JavaScript中的exportExcel函数
    """
    # 创建一个新的Excel工作簿
    workbook = Workbook()
    
    # 如果传入的是单个数据集而非对象
    if not isinstance(data_sheets, dict) or 'sheets' not in data_sheets:
        # 获取默认的工作表
        worksheet = workbook.active
        if worksheet:
            worksheet.title = "Sheet1"
        
        # 添加表头
        if data_sheets and len(data_sheets) > 0:
            # 过滤掉_isMonthEnd字段
            headers = [h for h in list(data_sheets[0].keys()) if h != '_isMonthEnd']
            for col_idx, header in enumerate(headers, 1):
                worksheet.cell(row=1, column=col_idx, value=header)# type: ignore[optional-member-access]
            
            # 添加数据
            for row_idx, row_data in enumerate(data_sheets, 2):
                for col_idx, header in enumerate(headers, 1):
                    worksheet.cell(row=row_idx, column=col_idx, value=row_data.get(header, ""))# type: ignore[optional-member-access]
    else:
        # 处理多个工作表
        # 删除默认创建的Sheet
        default_sheet = workbook.active
        if default_sheet is not None:
            workbook.remove(default_sheet)
        
        for sheet in data_sheets['sheets']:
            # 创建新的工作表
            worksheet = workbook.create_sheet(title=sheet['name'])
            
            # 添加表头 - 过滤掉_isMonthEnd字段
            if sheet['data'] and len(sheet['data']) > 0:
                headers = [h for h in list(sheet['data'][0].keys()) if h != '_isMonthEnd']
                for col_idx, header in enumerate(headers, 1):
                    worksheet.cell(row=1, column=col_idx, value=header)
                
                # 设置单元格样式（如果有标记的月末日期）
                has_month_end = any('_isMonthEnd' in row and row['_isMonthEnd'] for row in sheet['data'])
                
                # 添加数据
                for row_idx, row_data in enumerate(sheet['data'], 2):
                    for col_idx, header in enumerate(headers, 1):
                        cell = worksheet.cell(row=row_idx, column=col_idx, value=row_data.get(header, ""))
                        
                        # 如果是月末日期行，为日期单元格设置黄色背景
                        if has_month_end and row_data.get('_isMonthEnd') : #and (header == "订单确认时间")
                            from openpyxl.styles import PatternFill
                            cell.fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
                
                # 设置列宽
                if 'options' in sheet and 'columnWidth' in sheet['options']:
                    for col_letter, width in sheet['options']['columnWidth'].items():
                        # if col_letter in worksheet.column_dimensions:
                        worksheet.column_dimensions[col_letter].width = width
                
                # 添加自动筛选功能
                worksheet.column_dimensions['A'].bestFit = True
                
                # 添加自动筛选功能
                if 'options' in sheet and sheet['options'].get('autoFilter'):
                    # 设置筛选范围
                    max_row = len(sheet['data']) + 1  # +1 是因为有表头
                    max_col = len(headers)
                    filter_range = f"A1:{get_column_letter(max_col)}{max_row}"
                    worksheet.auto_filter.ref = filter_range
                    
                    # 如果有特定列的筛选条件
                    if isinstance(sheet['options']['autoFilter'], dict) and 'column' in sheet['options']['autoFilter']:
                        filter_column = sheet['options']['autoFilter']['column']
                        col_idx = get_column_index(worksheet, filter_column)
                        
                        if col_idx != -1:
                            # 在openpyxl中，列索引从0开始
                            col_letter = get_column_letter(col_idx + 1)
                            
                            # 创建筛选条件
                            filter_column = FilterColumn(colId=col_idx)
                            custom_filter = CustomFilter(operator='equal', val='1')
                            filter_column.customFilters = CustomFilters( None,[custom_filter])
                            worksheet.auto_filter.filterColumn.append(filter_column)
    
    # 保存工作簿
    workbook.save(export_file_name)
    print(f"Excel 文件导出成功！{export_file_name}")


def get_csv_data(file_path):
    """
    读取CSV文件数据
    相当于JavaScript中的getCSVData函数
    """
    global config
    results = []
    try:
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            channel = determine_channel(file_path)
            content = csvfile.readlines()
            # 查找真正的CSV头部行
            header_row = 0
            csv_header = config.get("keywords",[])
            for i, line in enumerate(content[:9]):
                # 检查是否是有效的CSV头部行
                if any(str(header) in line for header in csv_header):
                    header_row = i
                    break
            csv_reader = csv.DictReader(content[header_row:])
            for row in csv_reader:
                row.update({'来源':channel})
                results.append(row)
        print(f"CSV 读取完成，结果：{len(results)} 行")
        return results
    except Exception as e:
        print(f"读取错误: {e}")
        return []


def process_data(data, header, need_num, condition):
    """
    处理数据的通用函数
    相当于JavaScript中的processData函数
    """
    global config
    main_data = config.get("main_data", {})
    payment_filter=main_data.get("payment_status_filter",["部分退款", "已支付"])
    result = []
    for item in data:
        if item.get("支付状态") in payment_filter and condition(item):
            obj = {}
            for key in header:
                obj[key] = item.get(key, "")
                if key in need_num:
                    try:
                        obj[key] = float(obj[key].replace(',','')) if isinstance(obj[key], str) else float(obj[key])
                    except (ValueError, TypeError):
                        obj[key] = 0.0
            result.append(obj)
    return result

def get_export_filename(files, name=None):
    """
    根据输入文件名生成导出文件名
    相当于JavaScript中的getExportFileName函数
    """
    if name:
        return name
    if not files or len(files) == 0:
        return "数据汇总.xlsx"
    
    # 从第一个文件名提取前缀和日期范围（示例：NW店铺订单全部4.1-4.30.xlsx）
    file_name = os.path.basename(files[0])  # 获取纯文件名
    import re
    pattern = r'^([A-Za-z]{2,}).*?(\d+\.\d+-\d+\.\d+)'
    match = re.search(pattern, file_name)
    
    if not match:
        return "数据汇总.xlsx"
    
    prefix, date_range = match.groups()
    return f"{prefix}{date_range}汇总.xlsx"

def currency_sum(data, cur_field="货币单位", sum_field="订单总价"):
    """
    计算不同货币的总和
    相当于JavaScript中的currencySum函数
    """
    currency_obj = {}
    for item in data:
        if (item.get("计数") and item.get("计数") != 1):
           continue
        currency = item.get(cur_field)
        if currency:
            amount = item.get(sum_field, 0)
            try:
                amount = float(amount)
            except (ValueError, TypeError):
                amount = 0
            
            currency_obj[currency] = currency_obj.get(currency, 0) + amount
    return currency_obj
    # print("货币汇总:")
    # for currency, amount in currency_obj.items():
    #     print(f"{currency}: {amount}")
    # print("------------------------------------")

# 同时兼容两种格式读取
def get_data(file_path):
  file_ext = os.path.splitext(file_path)[1].lower()  
  if file_ext in ['.csv', '.CSV']:
    return get_csv_data(file_path)
  elif file_ext in ['.xlsx', '.xls']:
    return get_xlsx_data(file_path)
  else:
    return []
    # raise ValueError(f"不支持的文件格式: {file_ext}，请使用CSV或Excel文件")
# 对象深拷贝
def deep_merge(d1, d2):
    result = d1.copy()
    for k, v in d2.items():
        if k in result and isinstance(result[k], dict) and isinstance(v, dict):
            result[k] = deep_merge(result[k], v)
        else:
            result[k] = v
    return result    

def main(excel_files, pay_csv_arr_file, air_csv_arr_file, export_file_name=None):
    """
    主函数，处理Excel和CSV数据并导出结果
    相当于JavaScript中的main函数
    """
    global config
    # 读取Excel文件
    new_data = []
    for file_path in excel_files:
        data = get_data(file_path)
        # data = get_xlsx_data(file_path)
        new_data.extend(data)

    main_data = config.get("main_data", {})
    # 定义表头
    header =main_data.get('header', [
        "支付订单号",
        "货币单位",
        "订单总价",
        "商品总价",
        "优惠金额",
        "物流费用",
        "支付状态",
        "支付方式1",
        "支付渠道1",
        "支付金额1",
        "最后一次互动来源"
    ])
    need_num = main_data.get('numeric_fields',["订单总价", "商品总价", "优惠金额", "物流费用"])
    
    # 筛选条件1：部分退款或已支付，且支付渠道不是空中云汇
    pay_data = process_data(new_data, header, need_num, lambda item: item.get("支付渠道1") != "空中云汇")
    
    # 筛选条件2：对应云汇
    air_data = process_data(new_data, header, need_num, lambda item: item.get("支付渠道1") == "空中云汇")
    
    # 定义CSV数据的表头paypal_header
    header1 =main_data.get('paypal_header', ["交易号", "币种", "总额", "费用", "净额","类型", "状态","来源" ])
    checkout_types =main_data.get('paypal_checkout_types', ["快速结账付款", "直接信用卡付款", "预先批准付款账单用户付款"])
    checkout_status =main_data.get('paypal_checkout_status', ["已完成"])
    checkout_neednum =main_data.get('paypal_checkout_neednum', ["总额", "费用", "净额"])
    
    header2 =main_data.get('air_header', ["交易编号", "交易币种", "交易金额","授权状态返回描述", "交易状态","来源" ])
    checkout_types2 =main_data.get('air_checkout_types', ["FULLY REFUNDED", "PARTIALLY REFUNDED", "SUCCEEDED", "DISPUTED"])
    
    # 读取CSV数据
    # csv_data = get_csv_data(pay_csv_file)
       # 读取CSV数据
    csv_data = []
    for csv_file in pay_csv_arr_file:
        data = get_data(csv_file)
        csv_data.extend(data)
      
    # csv_data2 = get_csv_data(air_csv_file)
    csv_data2 = []
    for csv_file in air_csv_arr_file:
        data = get_data(csv_file)
        csv_data2.extend(data)
    
    # 处理PayPal数据
    pay_data2 = []
    for item in pay_data:
        is_repeat = False
        for csv_item in csv_data:
            is_same = csv_item.get("交易号",csv_item.get("Transaction ID",  "")) == item.get("支付订单号")
            if is_same:
                if csv_item.get("状态",csv_item.get("Status",  "")) in checkout_status and csv_item.get("类型",csv_item.get("Type",  "")) in checkout_types:
                    # 检查订单确认时间是否为月末
                    is_month_end = is_last_day_of_month(item.get("订单确认时间"))
                    
                    new_obj = {}
                    for key in header1:
                        new_obj[key] = csv_item.get(key, "")
                        # 将数值字段转换为浮点数
                        if key in checkout_neednum:
                            try:
                                new_obj[key] = float(new_obj[key].replace(',','')) if isinstance(new_obj[key], str) else float(new_obj[key])
                            except (ValueError, TypeError):
                                new_obj[key] = 0.0
                    
                    new_obj["计数"] = 1
                    if is_repeat:
                        new_obj["计数"] = new_obj.get("计数", 0) + 1
                    
                    # 如果是月末，添加标记
                    if is_month_end:
                        new_obj["_isMonthEnd"] = True
                        item["_isMonthEnd"] = True
                    
                    is_repeat = True
                    pay_data2.append(new_obj)
    
    # 处理云汇数据
    air_data2 = []
    for item in air_data:
        is_repeat = False
        for csv_item in csv_data2:
            is_same = csv_item.get("交易编号") == item.get("支付订单号")
            if is_same:
                if csv_item.get("交易状态") in checkout_types2:
                    # 检查订单确认时间是否为月末
                    is_month_end = is_last_day_of_month(item.get("订单确认时间"))
                    
                    new_obj = {}
                    for key in header2:
                        new_obj[key] = csv_item.get(key, "")
                        # 将数值字段转换为浮点数
                        if key in ["交易金额"]:
                            try:
                                # new_obj[key] = float(new_obj[key].replace(',',''))
                                new_obj[key] = float(new_obj[key].replace(',','')) if isinstance(new_obj[key], str) else float(new_obj[key])
                            except (ValueError, TypeError):
                                new_obj[key] = 0.0
                    
                    new_obj["计数"] = 1
                    if is_repeat:
                        new_obj["计数"] = new_obj.get("计数", 0) + 1
                    
                    # 如果是月末，添加标记
                    if is_month_end:
                        new_obj["_isMonthEnd"] = True
                        item["_isMonthEnd"] = True
                    
                    is_repeat = True
                    air_data2.append(new_obj)

    # 可选：计算货币汇总
    pay_sum= currency_sum(pay_data, "货币单位", "订单总价")
    air_sum= currency_sum(air_data, "货币单位", "订单总价")
    pay_sum2= currency_sum(pay_data2, "币种", "总额")
    air_sum2= currency_sum(air_data2, "交易币种", "交易金额")

    sum_obj=[pay_sum,air_sum,pay_sum2,air_sum2]
    currency_set=set()
    for item in sum_obj:
      currency_set.update(item.keys())
    
    total_data=[]
    for item in currency_set:
        obj={
          "币种": item,
          "店铺筛paypal": pay_sum.get(item,0),
          "paypal": pay_sum2.get(item,0) ,
          "店铺筛云汇": air_sum.get(item,0) ,
          "云汇": air_sum2.get(item,0) ,
        }
        total_data.append(obj)
    total_data.sort(key=lambda item:item['币种'])

    # 创建多工作表的Excel文件
    sheets_config = [
        {
            "name": "原始数据",
            "data": new_data,
            "options": {
                "header": 1,
                "autoFilter": True,
            }
        },
        {
            "name": "店铺筛Paypal",
            "data": pay_data,
            "options": {
                "header": 1,
                "columnWidth": {
                  'A': 20,
                },
                "autoFilter": True,
            }
        },
        {
            "name": "csv-PayPal",
            "data": pay_data2,
            "options": {
                "header": 1,
                  "columnWidth": {
                  'A': 20,
                },
                "autoFilter": True,
            }
        },
        {
            "name": "店铺筛云汇",
            "data": air_data,
            "options": {
                "header": 1,
                "columnWidth": {
                  'A': 25,
                },
                "autoFilter": True,
            }
        },
        {
            "name": "csv-云汇订单",
            "data": air_data2,
            "options": {
                "header": 1,
                "columnWidth": {
                  'A': 25,
                },
                "autoFilter": True,
            }
        },
        {
            "name": "汇总",
            "data": total_data,
            "options": {
                "header": 1,
                "columnWidth": {
                  'A': 10,
                  'B': 15,
                  'C': 15,
                  'D': 15,
                  'E': 15,
                },
            }
        },
      ]
    multi_sheet_data = {
      'sheets': sheets_config
    }
    # 获取导出文件名
    e_file_name = get_export_filename(excel_files, export_file_name)
    # 导出多工作表Excel文件
    output_file = create_filename(e_file_name)
    export_excel(multi_sheet_data, output_file)
    


def parse_arguments():
    """
    解析命令行参数
    """
    parser = argparse.ArgumentParser(description='Excel数据处理工具')
    parser.add_argument('--excel', nargs='+', required=True, help='Excel文件路径，可以指定多个文件')
    parser.add_argument('--paypal',nargs='+', required=True, help='PayPal CSV文件路径，可以指定多个文件')
    parser.add_argument('--air', nargs='+',required=True, help='云汇 CSV文件路径，可以指定多个文件')
    parser.add_argument('--output', required=False, help='输出Excel文件名')
    return parser.parse_args()


if __name__ == "__main__":
    
    if len(sys.argv) > 1:
        # 命令行模式
        args = parse_arguments()
        # 加载配置文件
        load_config()
        main(args.excel, args.paypal, args.air, args.output)
    else:
        # 交互模式
        while True:
            print("小娇娇Excel数据处理工具")
            print('*'*30,"注意事项",'*'*30)
            print('1.文件命名最好要规范')
            print('2.csv文件需要把头部无关信息删除,注意英文状态')
            print('3.csv文件支持转成xlsx文件读取')
            print('4.文件夹路径 在文件管理最上方输入框获取')
            print('5.命令行中 ↑ ↓ 箭头切换粘贴信息,鼠标右键直接粘贴选项')
            print('6.直接按 Enter 键结束')
            print('7.可以修改config.json配置文件自定义参数')
            print('8.查看当前相关文件 dir /b /s *.xlsx *.csv')
            print('*'*70)
            # print('当前相关文件(tree /f /a | findstr /i /r "\.xlsx$ \.csv$"):')
            # print(os.system('tree /f /a | findstr /i /r "\.xlsx$ \.csv$" '))

            # 检查是否存在配置文件，如果存在则加载
            config = load_config()
            # 检查配置文件中是否有预设的文件路径
            excel_files = config.get("file_paths", {}).get("excel_files", [])
            pay_csv_arr_file = config.get("file_paths", {}).get("paypal_csv_files", [])
            air_csv_arr_file = config.get("file_paths", {}).get("air_csv_files", [])
            export_file_name = config.get("output", {}).get("export_file_name", "")
            
            use_config = False
            #json 读取模式
            if excel_files and (pay_csv_arr_file or air_csv_arr_file):
                print("\n检测到配置文件中有预设的文件路径:")
                print("Excel文件:", ", ".join(excel_files))
                print("PayPal CSV文件:", ", ".join(pay_csv_arr_file))
                print("云汇 CSV文件:", ", ".join(air_csv_arr_file))
                use_config_choice = input("是否使用配置文件中的设置？(Y/N): ").strip().lower()
                if use_config_choice == 'y':
                    use_config = True
            
            if not use_config:
                print("\n请输入以下信息：")
                
                # 获取Excel文件路径
                excel_files = []
                while True:
                    excel_file = input("Excel店铺文件路径 (输入空行结束): ")
                    if not excel_file:
                        break
                    if os.path.exists(excel_file):
                        excel_files.append(excel_file)
                    else:
                        print(f"文件不存在: {excel_file}")
                
                if not excel_files:
                    print("错误：至少需要一个Excel文件")
                    sys.exit(1)
                
                # 获取PayPal CSV文件路径
                pay_csv_arr_file=[]
                while True:
                    pay_csv_file = input("PayPal CSV文件路径(输入空行结束): ")
                    if not pay_csv_file:
                        break
                    if os.path.exists(pay_csv_file):
                        pay_csv_arr_file.append(pay_csv_file)
                    else:
                      print(f"文件不存在: {pay_csv_file}")
                
                # 获取云汇CSV文件路径
                air_csv_arr_file=[]
                while True:
                    air_csv_file = input("云汇 CSV文件路径(输入空行结束): ")
                    if not air_csv_file:
                        break
                    if os.path.exists(air_csv_file):
                        air_csv_arr_file.append(air_csv_file)
                    else:
                      print(f"文件不存在: {air_csv_file}")
                
                # 获取输出文件名
                if not config["output"]["auto_name"]:
                  export_file_name = input("输出Excel文件名,需要后缀.xlsx (选填): ")
            
            # 执行主函数
            main(excel_files, pay_csv_arr_file, air_csv_arr_file, export_file_name)
            
            # 询问是否保存当前设置到配置文件
            # save_config_choice = input("\n是否将当前设置保存到配置文件？(Y/N): ").strip().lower()
            # if save_config_choice == 'y':
            #     config["file_paths"]["excel_files"] = excel_files
            #     config["file_paths"]["paypal_csv_files"] = pay_csv_arr_file
            #     config["file_paths"]["air_csv_files"] = air_csv_arr_file
            #     if export_file_name:
            #         config["output"]["export_file_name"] = export_file_name
            #         config["output"]["auto_name"] = False
                
            #     with open("config.json", 'w', encoding='utf-8') as f:
            #         json.dump(config, f, ensure_ascii=False, indent=2)
            #     print("设置已保存到config.json")
            
            continue_choice = input("\n是否继续处理下一批文件？(Y/N): ").strip().lower()
            if continue_choice != 'y':
                print("程序退出，感谢使用！")
                break